package com.zhong.controller;

import com.zhong.sao.ProviderSao;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author zbg on 2019-02-13 12:45:29
 */
@RestController
@RefreshScope
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MoviceController {

    @NonNull
    private ProviderSao providerSao;

    @Value("${spring.redis.host: defalut}")
    private String redisHost;

    @Value("${spring.datasource.username: defalut}")
    private String dbUserName;


    @GetMapping("/movice")
    public String movice(String id) {
        System.err.println("****************" + new Date());
        return providerSao.user(id);
    }

    @GetMapping("/config")
    public String config() {
        System.err.println("默认读取配置中心根目录下的application.yml" + redisHost);
        System.err.println("根据应用名读取各自的配置文件" + dbUserName);
        return redisHost + "***" + dbUserName;
    }

    @Autowired
    private LoadBalancerClient loadBalancer;
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 获取所有服务
     */
    @RequestMapping("/services")
    public Object services() {
        return discoveryClient.getInstances("microservice-21-provider");
    }

    /**
     * 从所有服务中选择一个服务（轮询）
     */
    @RequestMapping("/discover")
    public Object discover() {
        return loadBalancer.choose("microservice-21-provider").getUri().toString();
    }
}
